/*
 * SPI_transmit.c
 *
 * Created: 11.01.2014 14:34:16
 *  Author: Max
 */ 



#define F_CPU         8000000L 

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdint.h>

#include "UART_routines.h"


void uart0_init(void)
{
// 	/* Atmega 8 */
// 	UCSRB = 0x00; //disable while setting baud rate
// 	UCSRA = 0x00;
// 	UCSRC = (1 << URSEL) | 0x06;
// 	//  UBRRL = 0x33; //set baud rate lo orig.: 19
// 	//  UBRRH = 0x00; //set baud rate hi
// 	UBRRL = 0x19; //set baud rate 19200
// 	UBRRH = 0x00; //set baud rate hi
// 	UCSRB = 0x18;
	
	/* Atmega 328 */
	UCSR0B = 0x00; //disable while setting baud rate
	UCSR0A = 0x00;
	//UCSR0C = (1 << URSEL) | 0x06;
	/* Set frame format: 8data, 2stop bit */
	//UCSR0C = (1<<USBS0)|(3<<UCSZ00);
	UCSR0C = 3 << UCSZ00;
	UBRR0L = 0x33; //set baud rate lo 9600
	UBRR0H = 0x00; //set baud rate hi
	UCSR0B = _BV(TXEN0);
	//UCSR0B = 0x18;
	
}

void SPI_MasterInit(void)
{
	/* Set MOSI and SCK output, all others input */
	DDRB = (1<<3)|(1<<5);
	/* Enable SPI, Master */
	SPCR |= (1 << CPHA)|(1 << CPOL)|(1 << SPE)|(1 << MSTR);//|(1 << SPR1)|(1 << SPR0);
}


char SPI_MasterTransmit(char cData)
{
	/* Start transmission */
	SPDR = cData;
	/* Wait for transmission complete */
	while(!(SPSR & (1<<SPIF)));
	return SPDR;
}


int main(void)
{
	DDRB |= (1<<0);
	PORTB &= ~(1<<0);
	
// 
// 	while(1)
// 	{
// 		PORTB |= (1<<0);
// 		_delay_ms(50);
// 		PORTB &= ~(1<<0);
// 		_delay_ms(50);
// 		
// 	}
		
	char back;
	
	cli();
  	uart0_init();
	SPI_MasterInit();
	sei();
    
		transmitByte(11);
		TX_NEWLINE;
		
	
	while(1)
    {
		_delay_ms(200);
		back=SPI_MasterTransmit(3);
// 		for (int i=0; i<back;i++)
// 		{
// 			PORTB |= (1<<0);
// 			_delay_ms(20);
// 			PORTB &= ~(1<<0);
// 			_delay_ms(20);
// 		}

// 		transmitByte(back);
		
// 		if (back==123)
// 		{
// 			PORTB &= ~(1<<0);
// 		}
		
		_delay_ms(200);
		back=SPI_MasterTransmit(4);
		
// 		if (back==123)
// 		{
// 			PORTB |= (1<<0);			
// 		}

// 		transmitByte(back);
// 		TX_NEWLINE;
		
	}
}
